﻿using DotNet.Utilities;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace JiamituAPP {
    public partial class jiamitu : Form {

        #region 声明


        private readonly HttpHelper httpHelper = new HttpHelper();

        private readonly List<ResultData> ResultDatas = new List<JiamituAPP.ResultData>();

        private delegate void GetDataDelegate(object number);

        private Int32 pageFrom = 0;
        private Int32 pageTo = 0;
        /// <summary>
        /// 声明一个ContextMenuStrip控件，并初始化它
        /// </summary>
        private ContextMenuStrip strip = new ContextMenuStrip();//1
        private Thread myThread = null;
        /// <summary>
        /// 用于ListVie右键查看行时赋值
        /// </summary>
        private Int32 focusId = 0;
        public jiamitu() {
            InitializeComponent();
            this.lV_Content.Clear();  //从控件中移除所有项和列（包括列表头）。
            this.InitComboBox();
            this.Clear();
            this.InitListView();
            pageFrom = 0;
            pageTo = 0;
        }


        #endregion

        #region 清除列表数据



        /// <summary>
        /// 清除列表数据
        /// </summary>
        public void Clear() {
            // this.lV_Content.Clear();  //从控件中移除所有项和列（包括列表头）。

            this.lV_Content.Items.Clear();  //只移除所有的项。
        }

        #endregion

        #region 初始化数据

        /// <summary>
        /// 初始化ListView
        /// </summary>
        public void InitListView() {
            this.lV_Content.GridLines = true; //显示表格线
            this.lV_Content.View = View.Details;//显示表格细节
            this.lV_Content.LabelEdit = true; //是否可编辑,ListView只可编辑第一列。
            this.lV_Content.Scrollable = true;//有滚动条
            this.lV_Content.HeaderStyle = ColumnHeaderStyle.Clickable;//对表头进行设置
            this.lV_Content.FullRowSelect = true;//是否可以选择行

            //this.lV_Content.HotTracking = true;// 当选择此属性时则HoverSelection自动为true和Activation属性为oneClick
            //this.lV_Content.HoverSelection = true;
            //this.lV_Content.Activation = ItemActivation.Standard; //
            //添加表头
            this.lV_Content.Columns.Add("Id", 80);
            this.lV_Content.Columns.Add("几代", 80);
            this.lV_Content.Columns.Add("名称", 80);
            this.lV_Content.Columns.Add("价格", 80);
            this.lV_Content.Columns.Add("稀有度", 100);
            //添加各项
            //ListViewItem[] p = new ListViewItem[];
            //p[0] = new ListViewItem(new string[] { "", "aaaa", "bbbb" });
            //p[1] = new ListViewItem(new string[] { "", "cccc", "ggggg" });
            //p[0].SubItems[0].BackColor = Color.Red; //用于设置某行的背景颜色
            //this.lV_Content.Items.AddRange(p);
            //也可以用this.listView1.Items.Add();不过需要在使用的前后添加Begin... 和End...防止界面自动刷新
            // 添加分组
            //this.lV_Content.Groups.Add(new ListViewGroup("tou"));
            //this.lV_Content.Groups.Add(new ListViewGroup("wei"));

            //this.lV_Content.Items[0].Group = this.lV_Content.Groups[0];
            //this.lV_Content.Items[1].Group = this.lV_Content.Groups[1];
            //设置右键菜单
            strip.Items.Add("查看详情", null, DetailClicked);
            strip.Items.Add("购买");
            //增加点击事件
            // strip.ItemClicked += Strip_ItemClicked;
        }

        /// <summary>
        /// 初始化并绑定数据
        /// </summary>
        public void InitComboBox() {
            //数据绑定方式
            DataTable sourcettable = new DataTable();
            sourcettable.Columns.Add("Value");
            sourcettable.Columns.Add("Name");
            DataRow dr0 = sourcettable.NewRow();
            dr0["Value"] = "-1";
            dr0["Name"] = "全部";
            sourcettable.Rows.Add(dr0);
            DataRow dr1 = sourcettable.NewRow();
            dr1["Value"] = "0";
            dr1["Name"] = "普通";
            sourcettable.Rows.Add(dr1);
            DataRow dr2 = sourcettable.NewRow();
            dr2["Value"] = "1";
            dr2["Name"] = "稀有";
            sourcettable.Rows.Add(dr2);
            DataRow dr3 = sourcettable.NewRow();
            dr3["Value"] = "3";
            dr3["Name"] = "罕见";
            sourcettable.Rows.Add(dr3);
            DataRow dr4 = sourcettable.NewRow();
            dr4["Value"] = "5";
            dr4["Name"] = "史诗";
            sourcettable.Rows.Add(dr4);
            DataRow dr5 = sourcettable.NewRow();
            dr5["Value"] = "7";
            dr5["Name"] = "传说";
            sourcettable.Rows.Add(dr5);
            cb_rare.DataSource = sourcettable;//设置数据源
            cb_rare.DisplayMember = "Name";//设置显示列
            cb_rare.ValueMember = "Value";//设置实际值
            cb_rare.SelectedIndexChanged += new EventHandler(combobox_SelectedIndexChanged);
        }
        #endregion

        #region 触发事件

        /// <summary>
        /// 选择下拉
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void combobox_SelectedIndexChanged(object sender, EventArgs e) {
            ComboBox combobox = sender as ComboBox;
            //if (combobox != null) {
            //    MessageBox.Show(combobox.SelectedValue.ToString());
            //}
        }

        /// <summary>
        /// 清除列表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Clear_Click(object sender, EventArgs e) {
            this.Clear();
        }


        /// <summary>
        /// 开始获取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Start_Click(object sender, EventArgs e) {
            //HttpItem httpItem = new HttpItem() {
            //    URL = @"https://jiamitu.mi.com/pet/ng/listng?page=" + this.tb_PageTo.Text + "&limit=50&order=asc&orderBy=generation&rare=&followUp=https:%2F%2Fjiamitu.mi.com%2Fauction",
            //    Cookie = this.tb_Cooking.Text
            //};
            //var request = this.httpHelper.GetHtml(httpItem);
            //if (request.StatusCode == System.Net.HttpStatusCode.OK) {
            // var response = MapperHelper.DeserializeObject<Response>(request.Html);
            //this.StartThreading();
            if (!this.checkBox1.Checked) {
                this.Clear();
            }
            List<ResultData> dataList = new List<ResultData>();
            Int32 priceFrom = 0;
            Int32.TryParse(this.tb_PageFrom.Text, out priceFrom);
            Int32 priceTo = 0;
            Int32.TryParse(this.tb_priceTo.Text, out priceTo);
            dataList = ResultDatas;
            if (tb_generation.Text != "0") {
                Int32 generation = 0;
                Int32.TryParse(tb_generation.Text, out generation);
                dataList = ResultDatas.Where(x => x.generation == generation).ToList();
            }
            if (this.cb_rare.SelectedValue.ToString() != "-1") {
                dataList = ResultDatas.Where(x => x.rareDegree == this.cb_rare.Text).ToList();
            }
            this.ListViewData(dataList);
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Data_Click(object sender, EventArgs e) {
            this.StartThreading();
        }

        #region 定时器
        /// <summary>
        /// 定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e) {
            if (myThread.ThreadState == ThreadState.Stopped) {
                process(pageFrom);
                lb_foot.Text = "获取到 " + ResultDatas.Count() + " 条";
                this.timer1.Stop();
                this.ListViewData(ResultDatas);

            } else {
                process(pageFrom);
            }
        }
        #endregion

        /// <summary>
        /// ListView右键
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lV_Content_MouseClick(object sender, MouseEventArgs e) {
            if (e.Button == MouseButtons.Right) {
                strip.Show(lV_Content, e.Location);
                Int32.TryParse(((ListView)sender).FocusedItem.Text, out focusId);
            }

        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DetailClicked(object sender, EventArgs e) {
            HttpItem httpItem = new HttpItem() {
                URL = @"https://jiamitu.mi.com/pet/ng/getng?gid=" + focusId + "&followUp=https://jiamitu.mi.com/babydetail?petId=" + focusId + "#",
                Cookie = this.tb_Cooking.Text
            };
            var request = this.httpHelper.GetHtml(httpItem);
        }
        #endregion

        #region 方法

        /// <summary>
        /// 开始线程
        /// </summary>
        private void StartThreading() {
            Int32.TryParse(this.tb_PageFrom.Text, out pageFrom);
            Int32.TryParse(this.tb_PageTo.Text, out pageTo);

            myThread = new Thread(new ParameterizedThreadStart(GetData));
            myThread.IsBackground = true;
            myThread.Start(pageTo); //线程开始 
            this.timer1.Start();
        }

        /// <summary>
        /// 获取数据
        /// </summary>
        /// <returns></returns>
        private void GetData(object number) {
            pageFrom = 0;
            string rare = this.tb_generation.Text != "0"? "rare="+this.tb_generation.Text: "rare=";
            rare = rare != "0" ? rare : "rare=";
            for (pageFrom = 1; pageFrom <= pageTo; pageFrom++) {
                //System.Threading.Thread.Sleep(500);//暂停1秒
                HttpItem httpItem = new HttpItem() {
                    URL = @"https://jiamitu.mi.com/pet/data/list?page=" + pageFrom + "&limit=50&order=rare_degree&orderBy=desc&" + rare + "&followUp=https://jiamitu.mi.com/home",
                    Cookie = this.tb_Cooking.Text
                };
                var request = this.httpHelper.GetHtml(httpItem);
                if (request.StatusCode == System.Net.HttpStatusCode.OK) {
                    var response = MapperHelper.DeserializeObject<Response>(request.Html);
                    ResultDatas.AddRange(response.result.data);
                }
            }

        }

        /// <summary>
        /// 用于ListView赋值
        /// </summary>
        /// <param name="dataList"></param>
        private void ListViewData(List<ResultData> dataList) {
            Int32 priceFrom = 0;
            Int32.TryParse(this.tb_PageFrom.Text, out priceFrom);
            Int32 priceTo = 0;
            Int32.TryParse(this.tb_priceTo.Text, out priceTo);
            if (dataList.Count <= 0) {
                lb_foot.Text = "无数据";
            } else {
                lb_foot.Text = "";
            }
            Int32 Count = 0;
            foreach (var item in dataList) {

                if (item.price >= priceFrom && item.price <= priceTo) {

                    ListViewItem[] p = new ListViewItem[1];
                    //添加各项
                    p[0] = new ListViewItem(new string[] { item.id.ToString(), item.generation.ToString(), item.name, item.price.ToString(), item.rareDegree });
                    this.lV_Content.Items.AddRange(p);
                    Count++;

                }
            }
            lb_foot.Text = "匹配到" + Count + "条";
        }

        /// <summary>
        /// 委托
        /// </summary>
        /// <param name="i"></param>
        delegate void myDelegate(int i);
        myDelegate mydelegate = null;
        public void MyEvent() {
            for (int i = 0; i < 100; i++) {
                Thread.Sleep(100);
                this.BeginInvoke(mydelegate, new object[] { i });

            }
        }

        /// <summary>
        /// 进度条
        /// </summary>
        /// <param name="num"></param>
        public void process(Int32 num) {
            float value = ((float)pageFrom / (float)pageTo);
            num = (Int32)(value * 100);
            if (num <= 100)
                this.progressBar1.Value = num;
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="gid">加密兔id</param>
        public void Details(Int32 gid) {

        }


        #endregion

    }
}
